package com.yanqu.road.server.helper;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;

public class PlatformHttpHelper {
    private static Logger logger = LogManager.getLogger(PlatformHttpHelper.class.getName());
    //商会检测类型值定义
    public static final String UnionNameType = "1";
    public static final String UnionNoticeType = "2";
    /**
     * 平台检测昵称是否违规
     * @return
     */
    public static boolean platformCheckNickName(long serverId, String platformUserId, long userId, String nickName, String userIp, String appId,
                                                String appExt) {
        if (StringUtils.isNullOrEmpty(AppKeyMgr.getPlatformBaseUrl())) {//未配置sdk地址
            return false;
        }
        JSONObject paramObj = new JSONObject();
        try {
            paramObj.put("sid", serverId);//游戏区服
            paramObj.put("username", URLEncoder.encode(platformUserId, "UTF-8"));//玩家账号
            paramObj.put("actor", URLEncoder.encode(nickName, "UTF-8"));//角色名称
            paramObj.put("actor_id", userId);//角色ID
            paramObj.put("ip", userIp);//ip
            if(!StringUtils.isNullOrEmpty(appId) && !StringUtils.isNullOrEmpty(appExt)){
                String changeAppId = ServerListMgr.getChangeAppId(appId);
                paramObj.put("op", changeAppId);
                paramObj.put("app_ext", appExt);
            }
            paramObj.put("time", (System.currentTimeMillis() / 1000));

            SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
            String sign = SignHelper.getSign(paramMap, AppKeyMgr.getAndroidAppSecret());

            paramObj.put("sign", sign);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = AppKeyMgr.getPlatformBaseUrl() + "/chat/checkGameRoleName/" + AppKeyMgr.getAndroidAppId() + "/" + AppKeyMgr.getPlatformChannelId();
        logger.info("platformCheckNickName url:{}", url);
        Map<String, String> resultMap = HttpHelper.httpPostJson(url, paramObj.toJSONString(), "UTF-8", new HashMap<>(),
                ChannelConfig.CN_FORBIDDEN_WORD_CHECK_SOCKET_TIME_OUT,
                ChannelConfig.CN_FORBIDDEN_WORD_CHECK_CONNECT_TIME_OUT,
                ChannelConfig.CN_FORBIDDEN_WORD_CHECK_CONNECT_REQUEST_TIME_OUT);    //1秒超时时间
        boolean isForbidden = false;
        if(null == resultMap){
            logger.info("platformCheckNickName request error");     //请求出问题，返回未违规
        }else {
            String code = resultMap.get("code");
            logger.info("platformCheckNickName code:{}; result:{}", resultMap.get("code"), resultMap.get("body"));
            if("200".equals(code)){
                String resultStr = resultMap.get("body");
                if(!StringUtils.isNullOrEmpty(resultStr)) {
                    JSONObject resultObj = JSONObject.parseObject(resultStr);
                    int state = resultObj.getIntValue("state");
                    if (1 != state) {//状态码1表示不违规
                        isForbidden = true;
                    }
                }
            }
        }
        return isForbidden;
    }

    /**
     * 平台检测商会是否违规
     * @return
     */
    public static boolean platformCheckUnion(long serverId, String unionUid, String type, String content, String appId, String appExt) {
        if (StringUtils.isNullOrEmpty(AppKeyMgr.getPlatformBaseUrl())) {//未配置sdk地址
            return false;
        }
        JSONObject paramObj = new JSONObject();
        try {
            paramObj.put("sid", serverId);//游戏区服
            paramObj.put("guildid", unionUid);//商会编号
            paramObj.put("content", URLEncoder.encode(content, "UTF-8"));//内容
            paramObj.put("type", type);//类型：1：公会名；2：公会公告
            paramObj.put("time", (System.currentTimeMillis() / 1000));
            if(!StringUtils.isNullOrEmpty(appId)){
                String changeAppId = ServerListMgr.getChangeAppId(appId);
                paramObj.put("op", changeAppId);
            }

            SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
            String sign = SignHelper.getSign(paramMap, AppKeyMgr.getAndroidAppSecret());

            paramObj.put("sign", sign);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = AppKeyMgr.getPlatformBaseUrl() + "/chat/checkGameUnionName/" + AppKeyMgr.getAndroidAppId() + "/" + AppKeyMgr.getPlatformChannelId();
        logger.info("platformCheckUnion url:{}", url);
        Map<String, String> resultMap = HttpHelper.httpPostJson(url, paramObj.toJSONString(), "UTF-8", new HashMap<>(),
                ChannelConfig.CN_FORBIDDEN_WORD_CHECK_SOCKET_TIME_OUT,
                ChannelConfig.CN_FORBIDDEN_WORD_CHECK_CONNECT_TIME_OUT,
                ChannelConfig.CN_FORBIDDEN_WORD_CHECK_CONNECT_REQUEST_TIME_OUT);
        boolean isForbidden = false;
        if(null == resultMap){
            logger.info("platformCheckUnion request error");     //请求出问题，返回未违规
        }else {
            String code = resultMap.get("code");
            logger.info("platformCheckUnion code:{}; result:{}", resultMap.get("code"), resultMap.get("body"));
            if("200".equals(code)){
                String resultStr = resultMap.get("body");
                if(!StringUtils.isNullOrEmpty(resultStr)) {
                    JSONObject resultObj = JSONObject.parseObject(resultStr);
                    int state = resultObj.getIntValue("state");
                    if (1 != state) {//状态码1表示不违规
                        isForbidden = true;
                    }
                }
            }
        }
        return isForbidden;
    }
}
